<script>
export default {
  name: 'MbtiResult',
  data() {
    return {
      testResult: null,
      mbtiType: null,
      loading: true,
      error: null,
      errorMessage: '',
      isLoggedIn: false,
      isSaved: false,
      shareDialogVisible: false
    }
  },
  created() {
    this.checkLoginStatus()
    this.loadTestResult()
  },
  methods: {
    checkLoginStatus() {
      const userStr = localStorage.getItem('user')
      if (userStr) {
        try {
          const user = JSON.parse(userStr)
          this.isLoggedIn = !!user.userId
        } catch (e) {
          this.isLoggedIn = false
        }
      }
    },
    
    loadTestResult() {
      this.loading = true
      
      // 尝试从URL查询参数获取resultId
      const resultId = this.$route.query.resultId
      
      if (resultId) {
        // 如果URL中有resultId，直接通过ID获取测试结果
        console.log('从URL获取resultId:', resultId)
        this.getTestResultById(resultId)
      } else {
        // 尝试从localStorage获取最近的测试结果
        const lastResultStr = localStorage.getItem('lastTestResult')
        if (!lastResultStr) {
          this.error = '找不到测试结果'
          this.errorMessage = '请先完成MBTI测试'
          this.loading = false
          return
        }
        
        try {
          const lastResult = JSON.parse(lastResultStr)
          
          if (lastResult && lastResult.id) {
            this.getTestResultById(lastResult.id)
          } else {
            this.error = '测试结果数据不完整'
            this.errorMessage = '请重新进行测试'
            this.loading = false
          }
        } catch (e) {
          console.error('解析测试结果失败:', e)
          this.error = '解析测试结果失败'
          this.errorMessage = '请重新进行测试'
          this.loading = false
        }
      }
    },
    
    getTestResultById(id) {
      console.log('获取测试结果，ID:', id)
      
      this.$http.get(`/api/testResults/byId/${id}`)
        .then(response => {
          const { code, data } = response.data
          
          console.log('原始测试结果数据:', data)
          
          if (code === 200 && data) {
            this.testResult = this.processTestResult(data)
            console.log('处理后的测试结果数据:', this.testResult)
            
            if (this.testResult && this.testResult.mbtiType) {
              this.loadMbtiTypeDescription(this.testResult.mbtiType)
            } else {
              this.error = '测试结果数据不完整'
              this.errorMessage = '请重新进行测试'
              this.loading = false
            }
          } else {
            this.error = '获取测试结果失败'
            this.errorMessage = '请重新进行测试'
            this.loading = false
          }
        })
        .catch(error => {
          console.error('获取测试结果失败:', error)
          this.error = '获取测试结果失败'
          this.errorMessage = '请检查网络连接后重试'
          this.loading = false
        })
    },
    
    loadMbtiTypeDescription(mbtiType) {
      if (!mbtiType) {
        this.error = '无效的MBTI类型'
        this.errorMessage = '请重新进行测试'
        this.loading = false
        return
      }
      
      this.$http.get(`/api/mbti_type_description/${mbtiType}`)
        .then(response => {
          const { code, data } = response.data
          
          if (code === 200 && data) {
            this.mbtiType = data
          } else {
            this.error = '获取MBTI类型描述失败'
            this.errorMessage = '请稍后重试'
          }
        })
        .catch(error => {
          console.error('获取MBTI类型描述失败:', error)
          this.error = '获取MBTI类型描述失败'
          this.errorMessage = '请检查网络连接后重试'
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    saveResult() {
      if (!this.isLoggedIn || !this.testResult) return
      
      const userStr = localStorage.getItem('user')
      if (!userStr) return
      
      try {
        const user = JSON.parse(userStr)
        
        // 如果测试结果没有用户ID，则更新测试结果
        if (!this.testResult.userId) {
          const updateData = {
            id: this.testResult.id,
            userId: user.userId
          }
          
          this.$http.put('/api/testResults/byId', updateData)
            .then(response => {
              const { code } = response.data
              
              if (code === 200) {
                this.isSaved = true
                this.$message.success('测试结果保存成功')
                
                // 更新本地测试结果
                this.testResult.userId = user.userId
                localStorage.setItem('lastTestResult', JSON.stringify(this.testResult))
              } else {
                this.$message.error('保存测试结果失败')
              }
            })
            .catch(error => {
              console.error('保存测试结果失败:', error)
              this.$message.error('保存测试结果失败，请检查网络连接')
            })
        } else {
          this.isSaved = true
          this.$message.info('测试结果已保存')
        }
      } catch (e) {
        console.error('解析用户信息失败:', e)
      }
    },
    
    shareResult() {
      this.shareDialogVisible = true
    },
    
    copyShareLink() {
      // 实际项目中应该生成一个可分享的链接
      const shareLink = `${window.location.origin}/mbti-result?type=${this.testResult.mbtiType}`
      
      // 复制到剪贴板
      navigator.clipboard.writeText(shareLink)
        .then(() => {
          this.$message.success('链接已复制到剪贴板')
        })
        .catch(() => {
          this.$message.error('复制链接失败')
        })
    },
    
    formatDate(dateStr) {
      if (!dateStr) return '未知时间'
      
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    
    // 处理测试结果数据，确保分数字段格式正确
    processTestResult(data) {
      // 如果数据不存在，直接返回
      if (!data) return null;
      
      // 先打印原始数据，便于调试
      console.log('处理前的原始测试结果数据:', data);
      
      // 创建结果对象
      const result = { ...data };
      
      // 确保关键字段使用驼峰命名
      if (!result.mbtiType && result.mbtitype) {
        result.mbtiType = result.mbtitype;
      }
      
      // 确保所有分数字段都是数字类型
      const scoreFields = ['eScore', 'iScore', 'sScore', 'nScore', 'tScore', 'fScore', 'jScore', 'pScore'];
      const lowercaseFields = ['escore', 'iscore', 'sscore', 'nscore', 'tscore', 'fscore', 'jscore', 'pscore'];
      
      // 处理后端返回的小写字段，优先使用小写字段的值
      for (let i = 0; i < lowercaseFields.length; i++) {
        const lowercaseField = lowercaseFields[i];
        const camelCaseField = scoreFields[i];
        
        if (data[lowercaseField] !== undefined && data[lowercaseField] !== null) {
          // 将小写字段值转为数字并设置到驼峰字段
          const value = Number(data[lowercaseField]);
          result[camelCaseField] = isNaN(value) ? 0 : value;
          console.log(`从小写字段 ${lowercaseField}=${data[lowercaseField]} 设置 ${camelCaseField}=${result[camelCaseField]}`);
        }
        // 如果小写字段不存在但驼峰字段存在，确保驼峰字段为数字类型
        else if (data[camelCaseField] !== undefined && data[camelCaseField] !== null) {
          const value = Number(data[camelCaseField]);
          result[camelCaseField] = isNaN(value) ? 0 : value;
          console.log(`处理驼峰字段 ${camelCaseField}=${data[camelCaseField]} -> ${result[camelCaseField]}`);
        }
        // 如果两种字段都不存在，设置默认值0
        else {
          result[camelCaseField] = 0;
          console.log(`设置缺失字段 ${camelCaseField}=0`);
        }
      }
      
      // 计算各维度分数之和，用于计算百分比
      const eiSum = result.eScore + result.iScore;
      const snSum = result.sScore + result.nScore;
      const tfSum = result.tScore + result.fScore;
      const jpSum = result.jScore + result.pScore;
      
      // 添加百分比字段（用于前端显示）
      result.ePercentage = eiSum > 0 ? Math.round((result.eScore / eiSum) * 100) : 50;
      result.iPercentage = eiSum > 0 ? Math.round((result.iScore / eiSum) * 100) : 50;
      result.sPercentage = snSum > 0 ? Math.round((result.sScore / snSum) * 100) : 50;
      result.nPercentage = snSum > 0 ? Math.round((result.nScore / snSum) * 100) : 50;
      result.tPercentage = tfSum > 0 ? Math.round((result.tScore / tfSum) * 100) : 50;
      result.fPercentage = tfSum > 0 ? Math.round((result.fScore / tfSum) * 100) : 50;
      result.jPercentage = jpSum > 0 ? Math.round((result.jScore / jpSum) * 100) : 50;
      result.pPercentage = jpSum > 0 ? Math.round((result.pScore / jpSum) * 100) : 50;
      
      console.log('计算的百分比字段：', {
        E: result.ePercentage, I: result.iPercentage,
        S: result.sPercentage, N: result.nPercentage,
        T: result.tPercentage, F: result.fPercentage,
        J: result.jPercentage, P: result.pPercentage
      });
      
      // 调试日志
      console.log('处理后的测试结果数据:', result);
      
      return result;
    }
  }
}
</script>

<template>
  <div class="result-container">
    <div v-if="loading" class="loading">
      <el-skeleton :rows="10" animated></el-skeleton>
    </div>
    
    <div v-else-if="error" class="error-container">
      <el-result icon="error" :title="error" :sub-title="errorMessage">
        <template #extra>
          <el-button type="primary" @click="$router.push('/test')">重新测试</el-button>
          <el-button @click="$router.push('/home')">返回首页</el-button>
        </template>
      </el-result>
    </div>
    
    <div v-else-if="testResult && mbtiType" class="result-content">
      <div class="result-header">
        <h1>你的MBTI类型是: <span class="mbti-type">{{ testResult.mbtiType }}</span></h1>
        <h2 class="type-name">{{ mbtiType.typeName }}</h2>
      </div>
      
      <div class="card mb-20">
        <h3>类型描述</h3>
        <p>{{ mbtiType.description }}</p>
      </div>
      
      <div class="card mb-20">
        <h3>维度得分</h3>
        <div class="dimension-scores">
          <div class="dimension">
            <div class="dimension-pair">
              <div class="dimension-label">外向 (E)</div>
              <div class="dimension-bar">
                <div class="dimension-progress" :style="{width: `${testResult.ePercentage}%`}"></div>
              </div>
              <div class="dimension-value">{{ testResult.ePercentage || 0 }}%</div>
            </div>
            <div class="dimension-pair">
              <div class="dimension-label">内向 (I)</div>
              <div class="dimension-bar">
                <div class="dimension-progress" :style="{width: `${testResult.iPercentage}%`}"></div>
              </div>
              <div class="dimension-value">{{ testResult.iPercentage }}%</div>
            </div>
          </div>
          
          <div class="dimension">
            <div class="dimension-pair">
              <div class="dimension-label">实感 (S)</div>
              <div class="dimension-bar">
                <div class="dimension-progress" :style="{width: `${testResult.sPercentage}%`}"></div>
              </div>
              <div class="dimension-value">{{ testResult.sPercentage }}%</div>
            </div>
            <div class="dimension-pair">
              <div class="dimension-label">直觉 (N)</div>
              <div class="dimension-bar">
                <div class="dimension-progress" :style="{width: `${testResult.nPercentage}%`}"></div>
              </div>
              <div class="dimension-value">{{ testResult.nPercentage }}%</div>
            </div>
          </div>
          
          <div class="dimension">
            <div class="dimension-pair">
              <div class="dimension-label">思考 (T)</div>
              <div class="dimension-bar">
                <div class="dimension-progress" :style="{width: `${testResult.tPercentage}%`}"></div>
              </div>
              <div class="dimension-value">{{ testResult.tPercentage }}%</div>
            </div>
            <div class="dimension-pair">
              <div class="dimension-label">情感 (F)</div>
              <div class="dimension-bar">
                <div class="dimension-progress" :style="{width: `${testResult.fPercentage}%`}"></div>
              </div>
              <div class="dimension-value">{{ testResult.fPercentage }}%</div>
            </div>
          </div>
          
          <div class="dimension">
            <div class="dimension-pair">
              <div class="dimension-label">判断 (J)</div>
              <div class="dimension-bar">
                <div class="dimension-progress" :style="{width: `${testResult.jPercentage}%`}"></div>
              </div>
              <div class="dimension-value">{{ testResult.jPercentage }}%</div>
            </div>
            <div class="dimension-pair">
              <div class="dimension-label">感知 (P)</div>
              <div class="dimension-bar">
                <div class="dimension-progress" :style="{width: `${testResult.pPercentage}%`}"></div>
              </div>
              <div class="dimension-value">{{ testResult.pPercentage }}%</div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="card mb-20">
        <h3>性格模型</h3>
        <p>{{ mbtiType.model }}</p>
      </div>
      
      <div class="card mb-20">
        <h3>工作环境偏好</h3>
        <p>{{ mbtiType.workEnvironmentPreferences }}</p>
      </div>
      
      <div class="card mb-20">
        <h3>潜在弱点</h3>
        <p>{{ mbtiType.weakness }}</p>
      </div>
      
      <div class="card mb-20">
        <h3>发展建议</h3>
        <p>{{ mbtiType.developmentSuggestions }}</p>
      </div>
      
      <div class="card mb-20">
        <h3>适合领域</h3>
        <p>{{ mbtiType.filed }}</p>
      </div>
      
      <div class="card">
        <h3>职业建议</h3>
        <p>{{ mbtiType.career }}</p>
      </div>
      
      <div class="actions">
        <el-button type="primary" @click="$router.push('/test')">重新测试</el-button>
        <el-button @click="saveResult" :disabled="!isLoggedIn || isSaved">{{ isSaved ? '已保存' : '保存结果' }}</el-button>
        <el-button @click="shareResult">分享结果</el-button>
      </div>
    </div>
    
    <div v-else class="empty-state">
      <el-empty description="暂无测试结果"></el-empty>
      <el-button type="primary" @click="$router.push('/test')">开始测试</el-button>
    </div>
    
    <!-- 分享对话框 -->
    <el-dialog
      title="分享测试结果"
      :visible.sync="shareDialogVisible"
      width="400px"
      center
    >
      <div class="share-content">
        <p>你的MBTI类型是: <strong>{{ testResult?.mbtiType }}</strong> ({{ mbtiType?.typeName }})</p>
        <p>测试时间: {{ formatDate(testResult?.testTime) }}</p>
        <div class="qrcode-container">
          <p>扫描二维码分享给好友</p>
          <div class="qrcode-placeholder"></div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="shareDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="copyShareLink">复制链接</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped>
.result-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.loading, .error-container, .empty-state {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin-bottom: 20px;
}

.result-header {
  text-align: center;
  margin-bottom: 30px;
}

.result-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.mbti-type {
  color: #409EFF;
  font-weight: bold;
}

.type-name {
  font-size: 20px;
  color: #606266;
  margin-bottom: 20px;
}

h3 {
  font-size: 18px;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

p {
  color: #606266;
  line-height: 1.6;
}

.dimension-scores {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.dimension {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.dimension-pair {
  display: flex;
  align-items: center;
  gap: 10px;
}

.dimension-label {
  width: 80px;
  color: #606266;
  font-weight: bold;
}

.dimension-bar {
  flex: 1;
  height: 10px;
  background-color: #f5f7fa;
  border-radius: 5px;
  overflow: hidden;
}

.dimension-progress {
  height: 100%;
  background-color: #409EFF;
  border-radius: 5px;
}

.dimension-value {
  width: 50px;
  text-align: right;
  color: #606266;
}

.actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
}

.share-content {
  text-align: center;
}

.qrcode-container {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.qrcode-placeholder {
  width: 150px;
  height: 150px;
  background-color: #f5f7fa;
  border: 1px dashed #dcdfe6;
  margin-top: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.qrcode-placeholder::after {
  content: 'QR Code';
}
</style>